﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OperaHouse.Common;
using OperaHouse.Domain.Users;
using OperaHouse.Repository.Users;
using OperaHouse.DAL.Infrastructure;

namespace OperaHouse.Business.Users
{
    public partial class UserService : IUserService
    {
        #region Fields

        private readonly IUserRepository _userRepository;
        private readonly IUnitOfWork _unitOfWork;

        #endregion

        #region Ctor

        public UserService(IUserRepository userRepository, IUnitOfWork unitOfWork)
        {
            this._userRepository = userRepository;
            this._unitOfWork = unitOfWork;
        }

        #endregion

        #region Methods

        public virtual IList<User> GetAllUsers()
        {
            return _userRepository.GetAll().ToList();
        }

        public virtual IPagedList<User> FindUsers(string username, int pageIndex, int pageSize)
        {
            var query = _userRepository.Table;
            
            if (!String.IsNullOrWhiteSpace(username))
                query = query.Where(u => u.Username.Contains(username));

            query = query.OrderByDescending(u => u.Username);

            var users = new PagedList<User>(query, pageIndex, pageSize);
            return users;
        }

        public virtual User GetUserById(int id)
        {
            return _userRepository.GetById(id);
        }

        public virtual User GetUserLogin(string username, string password)
        {
            var query = from u in _userRepository.Table
                        orderby u.Id
                        where u.Username == username && u.Password == password
                        select u;
            var user = query.FirstOrDefault();
            return user;
        }

        public virtual void InsertUser(User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            _userRepository.Insert(user);
            _unitOfWork.Commit();
        }

        public virtual void UpdateUser(User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            _userRepository.Update(user);
            _unitOfWork.Commit();
        }

        public virtual void DeleteUser(User user)
        {
            if (user == null)
                throw new ArgumentNullException("user");

            _userRepository.Delete(user);
            _unitOfWork.Commit();
        }

        #endregion
    }
}
